package com.glela.statistics.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.StoreCenterEnum;
import com.glela.common.util.DateUtil;
import com.glela.common.util.StringUtils;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.model.User;
import com.glela.platform.service.UserService;
import com.glela.statistics.mapper.OrderStatisticsMapper;
import com.glela.statistics.model.*;
import com.glela.statistics.model.request.StoreCenterRequest;
import com.glela.statistics.model.response.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * V4.25
 * @author MaoZeYao
 *
 */
@Service("statisticsServiceImpl1")
@Order(1)
public class StatisticsServiceImpl1 extends AbstractStatisticsServiceImpl {
	
	@Autowired
	private OrderStatisticsMapper orderStatisticsMapper;
	
	@Autowired
	private UserMapper userMapper;

	@Autowired
	protected RedisUtil redisUtil;
	
	private String defaultTime = "2017-01-01";
	@Autowired
	private UserService userService;
	
	@Override
	public Map<String,Object> selectOrderInfoIds(String persionId, StoreCenterRequest selectCondition, User user) {
		// TODO Auto-generated method stub
		Map<String,Object> resModel = new HashMap<String,Object>();
		Map<String,Object> queryMap = new HashMap<String,Object>();

		if (user.getRoleId() < 7) {
			selectCondition.setOrderChannel(3);
		}
		
		// 查询订单归属过滤
		switch (selectCondition.getOrderChannel()) {
		case 1: //查所有
			queryMap.put("selectSelf", 1);
			queryMap.put("teacherPersion", persionId);
			break;
		case 2: // 查店主
			queryMap.put("selectSelf", 2);
			queryMap.put("teacherPersion", persionId);
			break;
		case 3: // 查自己
			queryMap.put("selectSelf", 3);
			queryMap.put("recommendFrom", persionId);
			break;
		default:
			break;
		}
		
		// 查询类别过滤
		if (!StringUtils.isEmpty(selectCondition.getKeyWord())) {
			switch (selectCondition.getRequestType()) {
			case 1:
				if ("P".equals(selectCondition.getKeyWord().substring(0,1)) || "p".equals(selectCondition.getKeyWord().substring(0,1))) {
					queryMap.put("selectOrderObject", StoreCenterEnum.SELECT_ORDER_OBJECT_SN.getCode());
					queryMap.put("orderObjectSn", "%" + selectCondition.getKeyWord().trim() + "%");
				} else {
					queryMap.put("selectOrder", StoreCenterEnum.SELECT_ORDERSN.getCode());
					queryMap.put("orderInfoSn", "%" + selectCondition.getKeyWord().trim() + "%");
				}
				break;
			case 2:
				queryMap.put("selectLinkMan", StoreCenterEnum.SELECT_NAME.getCode());
				queryMap.put("linkMan", "%" + selectCondition.getKeyWord().trim() + "%");
				break;
			case 3:
				queryMap.put("selectMobile", StoreCenterEnum.SELECT_MOBILE.getCode());
				queryMap.put("mobile", "%" + selectCondition.getKeyWord().trim() + "%");
				break;
			case 4:
				queryMap.put("selectGoodsName", StoreCenterEnum.SELECT_GOODS_NAME.getCode());
				queryMap.put("goodsName", "%" + selectCondition.getKeyWord().trim() + "%");
				break;
			default:
				break;
			}
		}
		
		/*// 订单状态条件过滤
		int array[];
		switch (selectCondition.getOrderStatus()) {
		case 1: // 待支付
			array = new int[] { 1 };
			break;
		case 2: // 待收货
			array = new int[] { 2, 3 };
			break;
		case 3: // 已收货
			array = new int[] { 4 };
			break;
		case 4: // 交易成功
			array = new int[] { 6 };
			break;
		case 5: // 交易失败
			array = new int[] { 7 };
			break;
		case 6: // 除去待支付的订单
			array = new int[] { 2, 3, 4, 6, 7 };
			break;
		default:
			array = new int[] { 1, 2, 3, 4, 6, 7 };
		}*/
		/*1待支付,2待发货,3待收货,4已完成,5取消,6交易成功,7交易关闭*/
		// 订单状态条件过滤------2018-01-24
		int array[];
		switch (selectCondition.getOrderStatus()) {
			case 1: // 待支付
				array = new int[] { 1 };
				break;
			case 2: // 待发货
				array = new int[] { 2 };
				break;
			case 3: // 待收货
				array = new int[] { 3 };
				break;
			case 4: // 已完成(包含交易成功)
				array = new int[] { 4,6 };
				break;
			case 5: // 交易失败
				array = new int[] { 7 };
				break;
			case 6: // 除去待支付的订单
				array = new int[] { 2, 3, 4, 6, 7 };
				break;
			default://查询所有。除了取消状态。
				array = new int[] { 1, 2, 3, 4, 6, 7 };
		}
		
		queryMap.put("statusArray", array);
		
		// 自营非自营过滤
		switch (selectCondition.getSelfSupport()) {
		case 0:
			queryMap.put("selectSelfSupport", selectCondition.getSelfSupport());
			break;
		case 1:
			queryMap.put("selectSelfSupport", selectCondition.getSelfSupport());
			break;
		default:
			queryMap.put("selectSelfSupport", 3);
			break;
		}
		
		// 时间过滤
		if (StringUtils.isEmpty(selectCondition.getStartTime())) {
			queryMap.put("startDate", defaultTime+" 00:00:00");
		} else {
			queryMap.put("startDate", selectCondition.getStartTime()+" 00:00:00");
		}

		if (StringUtils.isEmpty(selectCondition.getEndTime())) {
			queryMap.put("endDate", DateUtil.getFewDay(1)+" 00:00:00");
		} else {
			if (DateUtil.isToday(DateUtil.parse(selectCondition.getEndTime(), "yyyy-MM-dd"))) {
				queryMap.put("endDate", DateUtil.getFewDay(1)+" 00:00:00");
			} else {
				queryMap.put("endDate", selectCondition.getEndTime()+" 23:59:59");
			}
		}
		
		queryMap.put("startIndex", selectCondition.getStartIndex());
		queryMap.put("pageSize", selectCondition.getPageSize());
		
		if (selectCondition.getOrderChannel() == 1) {
			resModel.put("orderTotal", orderStatisticsMapper.selectOrderWithConditonTeacherTotal(queryMap));
			resModel.put("orderInfoIds", orderStatisticsMapper.selectOrderWithConditonTeacher(queryMap));
		} else {
			resModel.put("orderTotal", orderStatisticsMapper.selectOrderWithConditonTotal(queryMap));
			resModel.put("orderInfoIds", orderStatisticsMapper.selectOrderWithConditon(queryMap));
		}
		
		return resModel;
	}

	@Override
	public StoreCenterOrderResponse selectOrderDetailByOrderInfoIds(StoreCenterRequest selectCondition) {
		// TODO Auto-generated method stub
		//System.out.println("loginUserID:"+selectCondition.getLoginUserId()+"......>>>userID:"+selectCondition.getUserId()+"....渠道："+selectCondition.getOrderChannel());
		StoreCenterOrderResponse resModel = new StoreCenterOrderResponse();
		User user = userMapper.selectUserBaseInfoById(selectCondition.getUserId());
		User logUser = null;
		Map<String,Object> result = selectOrderInfoIds(user.getPersionId(), selectCondition, user);
		@SuppressWarnings("unchecked")
		List<Long> orderInfoIds = (List<Long>)result.get("orderInfoIds");
		OrderQueryTotal orderTotal = (OrderQueryTotal) result.get("orderTotal");
		
		if (orderInfoIds == null || orderInfoIds.size() < 1) {
			resModel.setOrderFee(orderTotal.getTotalSales());
			resModel.setGoodsNum(orderTotal.getGoodsNum());
			resModel.setOrderNum(orderTotal.getOrderNum());
			resModel.setOrderList(new ArrayList<TalentOrder>());
			return resModel;
		}
		
		boolean change = false;
		
		if (selectCondition.getLoginUserId() != selectCondition.getUserId()) {
			logUser = userMapper.selectUserBaseInfoById(selectCondition.getLoginUserId());
			if (logUser.getRoleId() == 7 && user.getRoleId() != 7) {
				change = true;
			}
		} else {
			logUser = user;
		}
		
		List<TalentOrderEntity> resultList = orderStatisticsMapper.selectOrderDetailByOrderInfoIds(user.getId(),orderInfoIds);
		List<TalentOrder> resOrder = new ArrayList<TalentOrder>();
		
		List<Long> orderInfoIdList = new ArrayList<Long>();

		for (TalentOrderEntity ids : resultList) {
			orderInfoIdList.add(ids.getOrderId());
		}
		orderInfoIdList = removeDuplicate(orderInfoIdList);
		for (Long orderInfoId : orderInfoIdList) {
			TalentOrder dealModel = new TalentOrder();
			dealModel.setOrderInfoId(orderInfoId);
			
			List<TalentOrderDetail> stepTwo = new ArrayList<TalentOrderDetail>();
			
			for (TalentOrderEntity talentOrderEntity : resultList) {
				if (talentOrderEntity.getOrderId() == orderInfoId) {
					dealModel.setCreateTime(talentOrderEntity.getCreateTime().substring(0,19));
					dealModel.setStatus(talentOrderEntity.getInfoStatus());
					dealModel.setOrderSn(talentOrderEntity.getOrderSn());
					dealModel.setSelfSupport(talentOrderEntity.getSelfSupport());
					dealModel.setOrderObjectSn(talentOrderEntity.getOrderObjectSn());
					if (talentOrderEntity.getCommissionStatus() == 1) {
						if (talentOrderEntity.getCommissionResult() == 1) {
							dealModel.setResult("已发");
						} else {
							dealModel.setResult("在途");
						}
					} else {
						if (talentOrderEntity.getCommission() > 0 || talentOrderEntity.getStudentCommission() > 0) {
							if (talentOrderEntity.getStatus() == 7) {
								dealModel.setResult("退款关闭");
							}
						} else {
							dealModel.setResult("");
						}
					}
					
					TalentOrderDetail stepThree = new TalentOrderDetail();
					if (change) {
						stepThree.setCommission(talentOrderEntity.getStudentCommission());
						stepThree.setStudentCommission(talentOrderEntity.getCommission());
					} else {
						stepThree.setCommission(talentOrderEntity.getCommission());
						stepThree.setStudentCommission(talentOrderEntity.getStudentCommission());
					}
					stepThree.setGoodsName(talentOrderEntity.getGoodName());
					stepThree.setGoodsImage(talentOrderEntity.getGoodsImage());
					stepThree.setOrderDetailId(talentOrderEntity.getOrderDetailId());
					stepThree.setQuantity(talentOrderEntity.getQuantity());
					stepThree.setSpecName(talentOrderEntity.getSpecName());
					stepThree.setStatus(talentOrderEntity.getStatus());
					stepThree.setTotalFee(talentOrderEntity.getTotalFee());
					stepThree.setSalePersion(talentOrderEntity.getSalePerson());
					
					if (logUser.getRoleId() < 7) {
						stepThree.setStudentCommission(0);
					}
					
					stepTwo.add(stepThree);
				}
			}
			dealModel.setOrderDetailList(stepTwo);
			resOrder.add(dealModel);
		}
		resModel.setOrderFee(orderTotal.getTotalSales());
		resModel.setGoodsNum(orderTotal.getGoodsNum());
		resModel.setOrderNum(orderTotal.getOrderNum());
		resModel.setOrderList(resOrder);
		
		return resModel;
	}

	@Override
	public ResponseWallet selectMyWallet(StoreCenterRequest selectCondition) {
		// TODO Auto-generated method stub
		ResponseWallet resModel = new ResponseWallet();
		User user = userMapper.selectByPrimaryKey(selectCondition.getUserId());
		
		if (user.getRoleId() < 3) {
			resModel.setJonurDetail(new ArrayList<CommissionResponse>());
			return resModel;
		}
		
		resModel.setMoney(user.getMoney());
		
		// 时间过滤
		if (StringUtils.isEmpty(selectCondition.getStartTime())) {
			selectCondition.setStartTime(defaultTime+" 00:00:00");
		} else {
			selectCondition.setStartTime(selectCondition.getStartTime()+" 00:00:00");
		}

		if (StringUtils.isEmpty(selectCondition.getEndTime())) {
			selectCondition.setEndTime(DateUtil.getFewDay(1)+" 00:00:00");
		} else {
			if (DateUtil.isToday(DateUtil.parse(selectCondition.getEndTime(), "yyyy-MM-dd"))) {
				selectCondition.setEndTime(DateUtil.getFewDay(1)+" 00:00:00");
			} else {
				selectCondition.setEndTime(selectCondition.getEndTime()+" 23:59:59");
			}
		}
		
		List<CommissionResponse> resList = orderStatisticsMapper.selectMyWalletByUserId(user.getId(),
				selectCondition.getStartTime(), selectCondition.getEndTime(), selectCondition.getStartIndex(),
				selectCondition.getPageSize());
		
		if (resList == null) {
			resModel.setJonurDetail(new ArrayList<CommissionResponse>());
		} else {
			resModel.setJonurDetail(resList);
		}
		
		if (user.getRoleId() < 3) {
			resModel.setJonurDetail(new ArrayList<CommissionResponse>());
			return resModel;
		}
		
		return resModel;
	}

	@Override
	public List<TalentStudent> selectStoreLink(long userId, int orderBy) {
		// TODO Auto-generated method stub
		User user = userMapper.selectUserBaseInfoById(userId);
		if (user.getRoleId() != 7) {
			return new ArrayList<TalentStudent>();
		}
		
		Map<String,Object> queryMap = new HashMap<String,Object>();
		queryMap.put("id", user.getId());
		queryMap.put("talentTeacher", user.getPersionId());
		List<TalentStudent> resModel = new ArrayList<TalentStudent>();
		if (orderBy == 0) {
			queryMap.put("defultSort", 1);
		}
		if (orderBy == 1) {
			queryMap.put("defultSort", 2);
		}
		if (orderBy == 2) {
			queryMap.put("defultSort", 3);
		}
		
		resModel = orderStatisticsMapper.selectStoreStudentLink(queryMap);
		
		if (resModel == null) {
			return resModel;
		}
		
		for (TalentStudent stu : resModel) {
			if ("".equals(stu.getRemark())) {
				stu.setRemark(stu.getUserName());
			}
		}
		
		return resModel;
	}

	@Override
	public List<TalentStudent> selectStoreCenterStudents(StoreCenterRequest selectCondition) {
		// TODO Auto-generated method stub
		User user = userMapper.selectUserBaseInfoById(selectCondition.getUserId());
		// 时间过滤
		Map<String,Object> queryMap = new HashMap<String,Object>();
		
		queryMap.put("id", user.getId());
		queryMap.put("talentTeacher", user.getPersionId());
		
		// 订单状态条件过滤
		int array[];
		switch (selectCondition.getOrderStatus()) {
		case 1: // 待支付
			array = new int[] { 1 };
			break;
		case 2: // 待收货
			array = new int[] { 2, 3 };
			break;
		case 3: // 已收货
			array = new int[] { 4 };
			break;
		case 4: // 交易成功
			array = new int[] { 6 };
			break;
		case 5: // 交易失败
			array = new int[] { 7 };
			break;
		default:
			array = new int[] {1, 2, 3, 4, 6 };
		}

		queryMap.put("statusArray", array);
		
		// 自营非自营过滤
		switch (selectCondition.getSelfSupport()) {
		case 0:
			queryMap.put("selectSelfSupport", selectCondition.getSelfSupport());
			break;
		case 1:
			queryMap.put("selectSelfSupport", selectCondition.getSelfSupport());
			break;
		default:
			queryMap.put("selectSelfSupport", 3);
			break;
		}
		
		// 时间过滤
		if (StringUtils.isEmpty(selectCondition.getStartTime())) {
			queryMap.put("startDate", defaultTime+" 00:00:00");
		} else {
			queryMap.put("startDate", selectCondition.getStartTime()+" 00:00:00");
		}

		if (StringUtils.isEmpty(selectCondition.getEndTime())) {
			queryMap.put("endDate", DateUtil.getFewDay(1)+" 00:00:00");
		} else {
			if (DateUtil.isToday(DateUtil.parse(selectCondition.getEndTime(), "yyyy-MM-dd"))) {
				queryMap.put("endDate", DateUtil.getFewDay(1)+" 00:00:00");
			} else {
				queryMap.put("endDate", selectCondition.getEndTime()+" 23:59:59");
			}
		}
		
		if (!StringUtils.isEmpty(selectCondition.getKeyWord())) {
			queryMap.put("selectNickName",1);
			queryMap.put("keyWord",selectCondition.getKeyWord());
		}
		
		if (selectCondition.getOrderBy() == 0) {
			selectCondition.setOrderBy(4);
		}
		
		// 排序
		switch (selectCondition.getOrderBy()) {
		case 1:
			queryMap.put("openAsc", 1);
			break;
		case 2:
			queryMap.put("openDesc", 2);
			break;
		case 3:
			queryMap.put("saleAsc", 1);
			break;
		case 4:
			queryMap.put("saleDesc", 2);
			break;
		default:
			break;
		}
		
		queryMap.put("startIndex", selectCondition.getStartIndex());
		queryMap.put("pageSize", selectCondition.getPageSize());
		
		return orderStatisticsMapper.selectStoreCenterStudents(queryMap);
	}

	@Override
	public RevenueResponse selectRevenueDetails(StoreCenterRequest selectCondition) {
		// TODO Auto-generated method stub
		RevenueResponse resModel = new RevenueResponse();
		Map<String,Object> queryMap = new HashMap<String,Object>();
		
		int totalSales = 0; // 总销售额
		
		int totalCommission = 0; // 总佣金
		
		int directSales = 0; // 直卖销售额
		
		int redirectSales = 0; // 间接销售额
		
		int directCommission = 0; // 直卖佣金
		
		int redirectCommission = 0; // 间接佣金
		
		int trueSelfSupport = 0; // 自营商品销售额
		
		int trueSelfSupportCommission = 0; // 自营商品佣金
		
		int falseSelfSupport = 0; // 非自营产品销售额
		
		int falseSelfSupportCommission = 0; // 非自营产品佣金
		
		User user = userMapper.selectUserBaseInfoById(selectCondition.getUserId());
		
		if (user.getRoleId() == 7) {
			queryMap.put("fromTeacher", 1);
			queryMap.put("teacherId", user.getId());
			queryMap.put("teacherPersion", user.getPersionId());
		} else {
			User teacherInfo = userMapper.selectUserBaseInfoByPersionId(user.getTalentTeacher());
			queryMap.put("fromStudent", 1);
			queryMap.put("teacherId", teacherInfo.getId());
			queryMap.put("studentPersion", user.getPersionId());
		}
		
		// 时间过滤
		if (StringUtils.isEmpty(selectCondition.getStartTime())) {
			queryMap.put("startDate", defaultTime+" 00:00:00");
		} else {
			queryMap.put("startDate", selectCondition.getStartTime()+" 00:00:00");
		}

		if (StringUtils.isEmpty(selectCondition.getEndTime())) {
			queryMap.put("endDate", DateUtil.getFewDay(1)+" 00:00:00");
		} else {
			if (DateUtil.isToday(DateUtil.parse(selectCondition.getEndTime(), "yyyy-MM-dd"))) {
				queryMap.put("endDate", DateUtil.getFewDay(1)+" 00:00:00");
			} else {
				queryMap.put("endDate", selectCondition.getEndTime()+" 23:59:59");
			}
		}
		
		queryMap.put("startIndex", selectCondition.getStartIndex());
		queryMap.put("pageSize", selectCondition.getPageSize());
		
		List<StoreRevenUser> resList = new ArrayList<StoreRevenUser>();
		
		List<RevenueUser> dealMode = new ArrayList<RevenueUser>();
		
		// 查询单个讲师信息
		if (user.getRoleId() == 7 && selectCondition.getPageNum() == 1) {
			RevenueUser teacherAdvancedInfo = orderStatisticsMapper.selectRevenueDetailsTeacher(queryMap);
			if (teacherAdvancedInfo != null) {
				dealMode.add(teacherAdvancedInfo);
			}
		}
		
		// 获取店主信息若身份为店主  这只返回店主的信息
		List<RevenueUser> studentsData = orderStatisticsMapper.selectRevenueDetails(queryMap);
		
		if (studentsData != null) {
			dealMode.addAll(studentsData);
		}
		
		if (dealMode.size() < 1) {
			resModel.setStoretList(new ArrayList<StoreRevenUser>());
//			return resModel;
		}
		
		for (RevenueUser stu : dealMode) {
			StoreRevenUser resStu = new StoreRevenUser();
			
			resStu.setUserId(stu.getUserId());
			resStu.setNickName(stu.getNickName());
			resStu.setUserName(stu.getUserName());
			resStu.setOpenTime(stu.getOpenTime());
			resStu.setPicture(stu.getPicture());
			resStu.setRemark(stu.getRemark());
			resStu.setRoleId(stu.getRoleId());
			resStu.setSales(stu.getTotalSales());
			resStu.setTrueSelfSupportSales(stu.getTureSelfSales());
			resStu.setFalesSelfSupportSales(stu.getFalseSelfSales());
			if (user.getRoleId() == 7) {
				resStu.setTrueSelfSupportCommission(stu.getTureSelfCommission());
				resStu.setFalesSelfSupportCommission(stu.getFalseSelfCommission());
			} else {
				resStu.setTrueSelfSupportCommission(stu.getStudentTureSelfCommission());
				resStu.setFalesSelfSupportCommission(stu.getStudentFalseSelfCommission());
			}
			resList.add(resStu);
			
			if (user.getRoleId() != 7) {
				totalSales = stu.getTotalSales(); // 总销售额
				
				trueSelfSupportCommission = stu.getStudentTureSelfCommission();
				
				falseSelfSupportCommission = stu.getStudentFalseSelfCommission();
				
				totalCommission = stu.getStudentTureSelfCommission() + stu.getStudentFalseSelfCommission(); // 总佣金
				
				directSales = stu.getTotalSales(); // 直卖销售额
				
				trueSelfSupport = stu.getTureSelfSales(); // 自营商品销售额
				
				trueSelfSupportCommission = stu.getStudentTureSelfCommission(); // 自营商品佣金
				
				falseSelfSupport = stu.getFalseSelfSales(); // 非自营产品销售额
				
				falseSelfSupportCommission = stu.getStudentFalseSelfCommission(); // 非自营产品佣金
				
				directCommission = stu.getStudentTureSelfCommission() + stu.getStudentFalseSelfCommission();
			}
			
		}
		
		// 获得计总信息
		if (user.getRoleId() == 7) {
			List<RevenueResponse> teacherAndStudent = orderStatisticsMapper.selectRevenueTotal(queryMap);
			if (!CollectionUtils.isEmpty(teacherAndStudent) && teacherAndStudent.size() > 1) {
				totalSales = teacherAndStudent.get(0).getTotalSales() + teacherAndStudent.get(1).getTotalSales();
				
				totalCommission = teacherAndStudent.get(0).getTrueSelfSupportCommission() 	// 讲师直接自营佣金
						+ teacherAndStudent.get(0).getFalseSelfSupportCommission()			// 讲师直接非自营佣金
						+ teacherAndStudent.get(1).getTrueSelfSupportCommission()			// 讲师间接自营
						+ teacherAndStudent.get(1).getFalseSelfSupportCommission();			// 讲师间接 非自营
				
				directSales = teacherAndStudent.get(0).getTrueSelfSupportSales()
						+ teacherAndStudent.get(0).getFalseSelfSupportSales();
				
				redirectSales = teacherAndStudent.get(1).getTrueSelfSupportSales()
						+ teacherAndStudent.get(1).getFalseSelfSupportSales();
				
				directCommission = teacherAndStudent.get(0).getTrueSelfSupportCommission()
						+ teacherAndStudent.get(0).getFalseSelfSupportCommission();
				
				redirectCommission = teacherAndStudent.get(1).getTrueSelfSupportCommission()
						+ teacherAndStudent.get(1).getFalseSelfSupportCommission();
				
				trueSelfSupport = teacherAndStudent.get(0).getTrueSelfSupportSales()
						+ teacherAndStudent.get(1).getTrueSelfSupportSales();
				
				falseSelfSupport = teacherAndStudent.get(0).getFalseSelfSupportSales()
						+ teacherAndStudent.get(1).getFalseSelfSupportSales();
				
				trueSelfSupportCommission = teacherAndStudent.get(0).getTrueSelfSupportCommission()
						+ teacherAndStudent.get(1).getTrueSelfSupportCommission();
				
				falseSelfSupportCommission = teacherAndStudent.get(0).getFalseSelfSupportCommission()
						+ teacherAndStudent.get(1).getFalseSelfSupportCommission();
			}
			
			
		}
		
		resModel.setTotalSales(totalSales);
		resModel.setTotalCommission(totalCommission);
		
		resModel.setDirectSales(directSales);
		resModel.setRedirectSales(redirectSales);
		
		resModel.setDirectCommission(directCommission);
		resModel.setRedirectCommission(redirectCommission);
		
		resModel.setTrueSelfSupportSales(trueSelfSupport);
		resModel.setFalseSelfSupportSales(falseSelfSupport);
		
		resModel.setTrueSelfSupportCommission(trueSelfSupportCommission);
		resModel.setFalseSelfSupportCommission(falseSelfSupportCommission);
		
		resModel.setStoretList(resList);
		
		return resModel;
	}

	@Override
	public List<TalentStudent> queryUnderStudent(Long userId, int orderBy) {
		User user = userMapper.selectUserBaseInfoById(userId);
		if (user.getRoleId() != 7) {
			return new ArrayList<TalentStudent>();
		}

		Map<String,Object> queryMap = new HashMap<String,Object>();
		queryMap.put("id", user.getId());
		queryMap.put("talentTeacher", user.getPersionId());
		List<TalentStudent> resModel = new ArrayList<TalentStudent>();
		if (orderBy == 0) {
			queryMap.put("defultSort", 1);
		}
		if (orderBy == 1) {
			queryMap.put("defultSort", 2);
		}
		if (orderBy == 2) {
			queryMap.put("defultSort", 3);
		}

		resModel = orderStatisticsMapper.selectUnderUser(queryMap);

		if (resModel == null) {
			return resModel;
		}

		for (TalentStudent stu : resModel) {
			if ("".equals(stu.getRemark())) {
				stu.setRemark(stu.getUserName());
			}
		}

		return resModel;
	}
	/**
	 * @Description: 查询我的店铺下的订单（只算直接佣金）
	 * @Author: zhangrenjie
	 * @Date: 2018/2/3 11:22
	 *
	 */
	@Override
	public StoreCenterOrderResponse selectOrderDetailByOrderInfoIdsNew(StoreCenterRequest selectCondition) {
		StoreCenterOrderResponse resModel = new StoreCenterOrderResponse();
//		User user = userMapper.selectUserBaseInfoById(selectCondition.getUserId());
		User user = userService.getUserById(selectCondition.getUserId());
		User logUser = null;
		Map<String,Object> result = selectOrderInfoIdsNew(user.getPersionId(), selectCondition, user);
		@SuppressWarnings("unchecked")
		List<Long> orderInfoIds = (List<Long>)result.get("orderInfoIds");
		OrderQueryTotal orderTotal = (OrderQueryTotal) result.get("orderTotal");

		if (orderInfoIds == null || orderInfoIds.size() < 1) {
			resModel.setOrderFee(orderTotal.getTotalSales());
			resModel.setGoodsNum(orderTotal.getGoodsNum());
			resModel.setOrderNum(orderTotal.getOrderNum());
			resModel.setOrderList(new ArrayList<TalentOrder>());
			return resModel;
		}

		boolean change = false;

		if (selectCondition.getLoginUserId() != selectCondition.getUserId()) {
			logUser = userMapper.selectUserBaseInfoById(selectCondition.getLoginUserId());
			if (logUser.getRoleId() == 7 && user.getRoleId() != 7) {
				change = true;
			}
		} else {
			logUser = user;
		}

		List<TalentOrderEntity> resultList = orderStatisticsMapper.selectOrderDetailByOrderInfoIds(user.getId(),orderInfoIds);
		List<TalentOrder> resOrder = new ArrayList<TalentOrder>();

		List<Long> orderInfoIdList = new ArrayList<Long>();

		for (TalentOrderEntity ids : resultList) {
			orderInfoIdList.add(ids.getOrderId());
		}
		orderInfoIdList = removeDuplicate(orderInfoIdList);
		for (Long orderInfoId : orderInfoIdList) {
			TalentOrder dealModel = new TalentOrder();
			dealModel.setOrderInfoId(orderInfoId);

			List<TalentOrderDetail> stepTwo = new ArrayList<TalentOrderDetail>();

			for (TalentOrderEntity talentOrderEntity : resultList) {
				if (talentOrderEntity.getOrderId() == orderInfoId) {
					dealModel.setCreateTime(talentOrderEntity.getCreateTime().substring(0,19));
					dealModel.setStatus(talentOrderEntity.getInfoStatus());
					dealModel.setOrderSn(talentOrderEntity.getOrderSn());
					dealModel.setSelfSupport(talentOrderEntity.getSelfSupport());
					dealModel.setOrderObjectSn(talentOrderEntity.getOrderObjectSn());
					if (talentOrderEntity.getCommissionStatus() == 1) {
						if (talentOrderEntity.getCommissionResult() == 1) {
							dealModel.setResult("已发");
						} else {
							dealModel.setResult("在途");
						}
					} else {
						if (talentOrderEntity.getCommission() > 0 || talentOrderEntity.getStudentCommission() > 0) {
							if (talentOrderEntity.getStatus() == 7) {
								dealModel.setResult("退款关闭");
							}
						} else {
							dealModel.setResult("");
						}
					}

					TalentOrderDetail stepThree = new TalentOrderDetail();
					if (change) {
						stepThree.setCommission(talentOrderEntity.getStudentCommission());
						stepThree.setStudentCommission(talentOrderEntity.getCommission());
					} else {
						stepThree.setCommission(talentOrderEntity.getCommission());
						stepThree.setStudentCommission(talentOrderEntity.getStudentCommission());
					}
					stepThree.setGoodsName(talentOrderEntity.getGoodName());
					stepThree.setGoodsImage(talentOrderEntity.getGoodsImage());
					stepThree.setOrderDetailId(talentOrderEntity.getOrderDetailId());
					stepThree.setQuantity(talentOrderEntity.getQuantity());
					stepThree.setSpecName(talentOrderEntity.getSpecName());
					stepThree.setStatus(talentOrderEntity.getStatus());
					stepThree.setTotalFee(talentOrderEntity.getTotalFee());
					stepThree.setSalePersion(talentOrderEntity.getSalePerson());

					if (logUser.getRoleId() < 7) {
						stepThree.setStudentCommission(0);
					}

					stepTwo.add(stepThree);
				}
			}
			dealModel.setOrderDetailList(stepTwo);
			resOrder.add(dealModel);
		}
        if (orderTotal != null ) {
            resModel.setOrderFee(orderTotal.getTotalSales());
            resModel.setGoodsNum(orderTotal.getGoodsNum());
            resModel.setOrderNum(orderTotal.getOrderNum());
        }
		resModel.setOrderList(resOrder);

		return resModel;
	}
	/**
	 * @Description: 根据登录用户（店主）查询其店铺下所有订单
	 * @Author: zhangrenjie
	 * @Date: 2018/2/3 11:29
	 *
	 */
	private Map<String, Object> selectOrderInfoIdsNew(String persionId, StoreCenterRequest selectCondition, User user) {
		Map<String,Object> resModel = new HashMap<String,Object>();
		Map<String,Object> queryMap = new HashMap<String,Object>();

//		if (user.getRoleId() < 7) {
//			selectCondition.setOrderChannel(3);
//		}
		//放入用户ID
		queryMap.put("openStoreUserId",user.getId());

		// 查询订单归属过滤
//		switch (selectCondition.getOrderChannel()) {
//			case 1: //查所有
//				queryMap.put("selectSelf", 1);
//				queryMap.put("teacherPersion", persionId);
//				break;
//			case 2: // 查店主
//				queryMap.put("selectSelf", 2);
//				queryMap.put("teacherPersion", persionId);
//				break;
//			case 3: // 查自己
//				queryMap.put("selectSelf", 3);
//				queryMap.put("recommendFrom", persionId);
//				break;
//			default:
//				break;
//		}

		// 查询类别过滤
		if (!StringUtils.isEmpty(selectCondition.getKeyWord())) {
			switch (selectCondition.getRequestType()) {
				case 1:
					if ("P".equals(selectCondition.getKeyWord().substring(0,1)) || "p".equals(selectCondition.getKeyWord().substring(0,1))) {
						queryMap.put("selectOrderObject", StoreCenterEnum.SELECT_ORDER_OBJECT_SN.getCode());
						queryMap.put("orderObjectSn", "%" + selectCondition.getKeyWord().trim() + "%");
					} else {
						queryMap.put("selectOrder", StoreCenterEnum.SELECT_ORDERSN.getCode());
						queryMap.put("orderInfoSn", "%" + selectCondition.getKeyWord().trim() + "%");
					}
					break;
				case 2:
					queryMap.put("selectLinkMan", StoreCenterEnum.SELECT_NAME.getCode());
					queryMap.put("linkMan", "%" + selectCondition.getKeyWord().trim() + "%");
					break;
				case 3:
					queryMap.put("selectMobile", StoreCenterEnum.SELECT_MOBILE.getCode());
					queryMap.put("mobile", "%" + selectCondition.getKeyWord().trim() + "%");
					break;
				case 4:
					queryMap.put("selectGoodsName", StoreCenterEnum.SELECT_GOODS_NAME.getCode());
					queryMap.put("goodsName", "%" + selectCondition.getKeyWord().trim() + "%");
					break;
				default:
					break;
			}
		}
		/*1待支付,2待发货,3待收货,4已完成,5取消,6交易成功,7交易关闭*/
		// 订单状态条件过滤------2018-01-24
		int array[];
		switch (selectCondition.getOrderStatus()) {
			case 1: // 待支付
				array = new int[] { 1 };
				break;
			case 2: // 待发货
				array = new int[] { 2 };
				break;
			case 3: // 待收货
				array = new int[] { 3 };
				break;
			case 4: // 已完成(包含交易成功)
				array = new int[] { 4,6 };
				break;
			case 5: // 交易失败
				array = new int[] { 7 };
				break;
			case 6: // 除去待支付的订单
				array = new int[] { 2, 3, 4, 6, 7 };
				break;
			default://查询所有。除了取消状态。
				array = new int[] { 1, 2, 3, 4, 6, 7 };
		}

		queryMap.put("statusArray", array);

		// 自营非自营过滤
//		switch (selectCondition.getSelfSupport()) {
//			case 0:
//				queryMap.put("selectSelfSupport", selectCondition.getSelfSupport());
//				break;
//			case 1:
//				queryMap.put("selectSelfSupport", selectCondition.getSelfSupport());
//				break;
//			default:
//				queryMap.put("selectSelfSupport", 3);
//				break;
//		}

		// 时间过滤
		if (StringUtils.isEmpty(selectCondition.getStartTime())) {
			queryMap.put("startDate", defaultTime+" 00:00:00");
		} else {
			queryMap.put("startDate", selectCondition.getStartTime()+" 00:00:00");
		}

		if (StringUtils.isEmpty(selectCondition.getEndTime())) {
			queryMap.put("endDate", DateUtil.getFewDay(1)+" 00:00:00");
		} else {
			if (DateUtil.isToday(DateUtil.parse(selectCondition.getEndTime(), "yyyy-MM-dd"))) {
				queryMap.put("endDate", DateUtil.getFewDay(1)+" 00:00:00");
			} else {
				queryMap.put("endDate", selectCondition.getEndTime()+" 23:59:59");
			}
		}

		queryMap.put("startIndex", selectCondition.getStartIndex());
		queryMap.put("pageSize", selectCondition.getPageSize());

//		if (selectCondition.getOrderChannel() == 1) {
//			resModel.put("orderTotal", orderStatisticsMapper.selectOrderWithConditonTeacherTotal(queryMap));
//			resModel.put("orderInfoIds", orderStatisticsMapper.selectOrderWithConditonTeacher(queryMap));
//		} else {
//			resModel.put("orderTotal", orderStatisticsMapper.selectOrderWithConditonTotal(queryMap));
//			resModel.put("orderInfoIds", orderStatisticsMapper.selectOrderWithConditon(queryMap));
//		}
		//查询所有店铺下边的订单数据
//		OrderQueryTotal total = getOrderQueryTotal(user, queryMap);
//		resModel.put("orderTotal", total);
		resModel.put("orderTotal", orderStatisticsMapper.selectOrderWithConditonTotalByOpenStoreUserId(queryMap));
		resModel.put("orderInfoIds", orderStatisticsMapper.selectOrderWithConditonDetailByOpenStoreUserId(queryMap));
		return resModel;

	}
	/**
	 * @Description: 默认查询条件下--店铺总订单数，总金额，总商品数（并写入缓存）
	 * @Author: zhangrenjie
	 * @Date: 2018/3/8 11:45
	 *
	 */
	public OrderQueryTotal selectOrderTotal(StoreCenterRequest selectCondition) {
//		User user = userMapper.selectUserBaseInfoById(selectCondition.getUserId());
		User user = userService.getUserById(selectCondition.getUserId());
		Map<String,Object> queryMap = new HashMap<String,Object>();
		queryMap.put("openStoreUserId",user.getId());
		// 查询类别过滤
		if (!StringUtils.isEmpty(selectCondition.getKeyWord())) {
			switch (selectCondition.getRequestType()) {
				case 1:
					if ("P".equals(selectCondition.getKeyWord().substring(0,1)) || "p".equals(selectCondition.getKeyWord().substring(0,1))) {
						queryMap.put("selectOrderObject", StoreCenterEnum.SELECT_ORDER_OBJECT_SN.getCode());
						queryMap.put("orderObjectSn", "%" + selectCondition.getKeyWord().trim() + "%");
					} else {
						queryMap.put("selectOrder", StoreCenterEnum.SELECT_ORDERSN.getCode());
						queryMap.put("orderInfoSn", "%" + selectCondition.getKeyWord().trim() + "%");
					}
					break;
				case 2:
					queryMap.put("selectLinkMan", StoreCenterEnum.SELECT_NAME.getCode());
					queryMap.put("linkMan", "%" + selectCondition.getKeyWord().trim() + "%");
					break;
				case 3:
					queryMap.put("selectMobile", StoreCenterEnum.SELECT_MOBILE.getCode());
					queryMap.put("mobile", "%" + selectCondition.getKeyWord().trim() + "%");
					break;
				case 4:
					queryMap.put("selectGoodsName", StoreCenterEnum.SELECT_GOODS_NAME.getCode());
					queryMap.put("goodsName", "%" + selectCondition.getKeyWord().trim() + "%");
					break;
				default:
					break;
			}
		}
		/*1待支付,2待发货,3待收货,4已完成,5取消,6交易成功,7交易关闭*/
		int array[];array = new int[] { 1, 2, 3, 4, 6, 7 };
		queryMap.put("statusArray", array);
		// 时间过滤
		if (StringUtils.isEmpty(selectCondition.getStartTime())) {
			queryMap.put("startDate", defaultTime+" 00:00:00");
		} else {
			queryMap.put("startDate", selectCondition.getStartTime()+" 00:00:00");
		}
		if (StringUtils.isEmpty(selectCondition.getEndTime())) {
			queryMap.put("endDate", DateUtil.getFewDay(1)+" 00:00:00");
		} else {
			if (DateUtil.isToday(DateUtil.parse(selectCondition.getEndTime(), "yyyy-MM-dd"))) {
				queryMap.put("endDate", DateUtil.getFewDay(1)+" 00:00:00");
			} else {
				queryMap.put("endDate", selectCondition.getEndTime()+" 23:59:59");
			}
		}
		//查询所有店铺下边的订单统计数据
		OrderQueryTotal total = getOrderQueryTotal(user, queryMap);
		return total;

	}

	private OrderQueryTotal getOrderQueryTotal(User user, Map<String, Object> queryMap) {
		OrderQueryTotal total = null;
		String rslt = null;
		String tempKey = "user_store_order_totals : "+user.getId();
		rslt = redisUtil.get(tempKey);
		if (StringUtils.isEmpty(rslt)) {
			try {
				total = orderStatisticsMapper.selectOrderWithConditonTotalByOpenStoreUserId(queryMap);
//				rslt = JsonUtil.toJson(total);
				rslt = JSONObject.toJSONString(total);
				redisUtil.set(tempKey,rslt,20);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			try {
//				Object o = JsonUtil.toBean(rslt, Class.forName("com.glela.statistics.model.OrderQueryTotal"));
//				total = (OrderQueryTotal) o;
				OrderQueryTotal orderQueryTotal = JSONObject.parseObject(rslt, OrderQueryTotal.class);
				total = orderQueryTotal;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (total == null) {
			total = new OrderQueryTotal();
		}
		return total;
	}
}
